package com.maoxx.libms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.maoxx.libms.controller.dto.RecordDto;
import com.maoxx.libms.entity.User;
import com.maoxx.libms.service.IUserService;
import com.maoxx.libms.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2024-10-25
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController{

    @Autowired
    private IUserService userService;

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/view")
    public String view(){
        return "page/user";
    }

    @RequestMapping("/book/bookAdd")
    public String test() {
        return "page/book_add";
    }


    /**
     * 获取所有用户
     * @return 用户列表
     */
    @GetMapping()
    @ResponseBody
    public Result<List<User>> getAllUsers(){
        List<User> list = userService.list();
        return Result.success(list);
    }


    /**
     * 获取所有用户借阅记录
     * @param page 当前页
     * @param pageSize 每页大小
     * @return 用户记录
     */
    @GetMapping("/record")
    @ResponseBody
    public Result<PageInfo<RecordDto>> getAllUsersRecord(Integer page, Integer pageSize){
        log.info("page:{},pageSize:{}",page,pageSize);
        PageInfo<RecordDto> pageInfo = userService.getAllUsersRecord(page, pageSize);
        return Result.success(pageInfo);
    }


    /**
     * 更新用户信息
     * @param user 用户信息
     * @return json结果
     */
    @PutMapping()
    @ResponseBody
    public Result<String> updateUser(@RequestBody User user){
        System.out.println("=+++++" + user.toString());
        boolean update = userService.updateUser(user);
        if(!update){
            return Result.error("更新失败");
        }
        return Result.success("更新成功");
    }

    /**
     * 添加用户
     * @param user 用户信息
     * @return Result
     */
    @PostMapping()
    @ResponseBody
    public Result<String> addUser(@RequestBody User user){
        boolean save = userService.save(user);
        if(!save){
            return Result.error("添加失败");
        }
        return Result.success("添加成功");
    }


    /**
     * 删除用户
     * @param id 用户id
     * @return 返回结果
     */
    @DeleteMapping("/delete")
    @ResponseBody
    public Result<String> deleteUser(Integer id){
        boolean remove = userService.removeById(id);
        if(!remove){
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }


}
